<?php


namespace App\Http\Controllers\applets\service;

use App\Http\Controllers\admin\service\AccountCenterService;
use App\Http\Controllers\applets\model\AdminSnModel;
use App\Http\Controllers\applets\model\BindSnModel;
use App\Http\Controllers\applets\model\GroupModel;
use App\Http\Controllers\applets\model\AdminModel;
use App\Http\Controllers\applets\model\BatchModel;
use App\Http\Controllers\applets\model\ParentSnModel;
use App\Http\Controllers\applets\model\SmsModel;
use App\Http\Controllers\applets\model\SnGradeModel;
use App\Http\Controllers\applets\model\TeacherSnModel;
use App\Http\Controllers\utils\LogUtil;
use App\Http\Controllers\utils\ToolUtil;
use Illuminate\Support\Facades\DB;

/**
 * 用户信息逻辑类
 * Class UserInfoService
 * @package App\Http\Controllers\applets\service
 */
class UserInfoService
{

    /**
     * 验证码登录
     * @param $param
     * @return false|string
     */
    public static function codeLogin($param){

        $param['phone'] = ToolUtil::filterStr($param['phone']);
        $param['code'] = ToolUtil::filterStr($param['code']);

        if(empty($param['type_id'])){
            return ToolUtil::returnJson(401,'类型为空');
        }

        $type_id = (int)$param['type_id'];
        $t_group = Db::table('t_group')->where('id',$type_id)->first(['group_id']);
        if(empty($t_group)){
            return ToolUtil::returnJson(401,'没有类型记录');
        }
        if($t_group['group_id'] !== 4){
            return ToolUtil::returnJson(401,'不是个人类型');
        }

        $code = SmsModel::queryFirst(['phone'=>$param['phone'],'code'=>$param['code'],'type'=>1],['id','create_time','is_use']);
        if(empty($code)){
            return ToolUtil::returnJson(303,'登录验证码不正确');
        }
        if($code['is_use'] === 1){
            return ToolUtil::returnJson(306,'登录验证码已使用过');
        }

        $update_sms = SmsModel::edit(['id'=>$code['id']],['is_use'=>1]);
        if(empty($update_sms)){
            return ToolUtil::returnJson(307,'数据错误');
        }

        if((time()-300) > (int)$code['create_time']){
            return ToolUtil::returnJson(304,'验证码时间超出');
        }

        $admin = AdminModel::queryFirst(['mobile'=>$param['phone'],'t_group_id'=>$type_id],['id','status','login_status','group_id','t_group_id','username','sn_num']);

        try {

            if($admin){

                $param['remark'] = '小程序手机验证码登录';
                return self::checkCodeLoginData($admin,$param);

            }else{

                $admin = [
                    'username'=>$param['phone'],
                    'password'=>'',
                    'mobile'=>$param['phone'],
                    'rand_num'=>'',
                    'group_id'=>4,
                    't_group_id'=>$type_id,
                    'create_time'=>time(),
                    'vip_id'=>4,
                    'status'=>1
                ];
                
                return self::checkCodeRegData($admin,$param);
            }

        }catch (\Exception $exception){
            DB::rollBack();
            return ToolUtil::returnJson(500,'登录失败');
        }
        
    }


    /**
     * 发送手机验证码登录的验证码
     * @param $param
     * @return false|string
     */
    public static function getLoginCode($param){

        $phone = ToolUtil::filterStr($param['phone']);
        $tem_code = 'SMS_219390206';

        $res = ToolUtil::aliSms($phone,$tem_code,1);

        return ToolUtil::returnJson($res['code'],$res['msg']);

    }


    /**
     * 处理验证码注册数据
     * @param $admin
     * @param $param
     * @return false|string
     */
    public static function checkCodeRegData($admin,$param){

        $uid = AdminModel::insertGetId($admin);
        if($uid){
            $data = [
                "id"=>$uid,//用户编号
                "username"=>$param['phone'],//用户名
                "sn_num"=>0,//设备总数量
                "group_id"=>$admin['group_id'],
                "t_group_id"=>$admin['t_group_id'],
            ];

            $data['sn'] = [];
            return ToolUtil::returnJson(200,'登录成功',$data);
        }
        return ToolUtil::returnJson(300,'登录失败');

    }    


    /**
     * 处理验证码登录数据
     * @param $admin
     * @param $param
     * @return false|string
     */
    public static function checkCodeLoginData($admin,$param){

        if($admin['status']===0){
            return ToolUtil::returnJson(301,'账号冻结中，请联系管理员');
        }
        if($admin['status']===2){
            return ToolUtil::returnJson(301,'账号没有通过审核，请联系管理员');
        }

        if($admin['login_status']===1){
            $loginStatus = 2;
        }elseif ($admin['login_status']===2){
            $loginStatus = 1;
        }else{
            $loginStatus = 1;
        }

        $data = [
            "id"=>$admin['id'],//用户编号
            "username"=>$admin['username'],//用户名
            "sn_num"=>$admin['sn_num'],//设备总数量
            "group_id"=>$admin['group_id'],//3老师，4家长
            "t_group_id"=>$admin['t_group_id'],
        ];

        $data['equipment'] = [];
        $data['sn'] = [];

        $parentSn = ParentSnModel::queryWhere(['admin_id'=>$data['id']],['t_parent_sn.id','online','avatar','name','value as sn_value']);
        if(count($parentSn)){
            $arr = [];
            foreach ($parentSn as $key=>$value){
                $arr[$key] = $value;
            }
            $data['sn'] = $arr;
        }
        
        $param['userId'] = $admin['id'];
        $param['details'] = ToolUtil::handleSuccessOrError(['mobile'=>$param['phone']]);
        LogUtil::addAdminLog($param);
        AdminModel::edit(['id'=>$admin['id']],['login_ip'=>$param['lastIp'],'login_time'=>time(),'login_status'=>$loginStatus]);
        return ToolUtil::returnJson(200,'登录成功',$data);

    }


    /**
     * 小程序登录
     * @param $param
     * @return false|string
     */
    public static function login($param){

        if(empty($param['type_id'])){
            return ToolUtil::returnJson(401,'类型为空');
        }

        $type_id = (int)$param['type_id'];
        $t_group = Db::table('t_group')->where('id',$type_id)->first(['group_id']);
        if(empty($t_group)){
            return ToolUtil::returnJson(401,'没有类型记录');
        }
        if($t_group['group_id'] !== 4){
            return ToolUtil::returnJson(401,'不是个人类型');
        }

        $param['username'] = ToolUtil::filterStr($param['username']);
        $t_admin = Db::table('t_admin')->where('t_group_id',$type_id)->where('mobile',$param['username'])->first(['id','rand_num','status','login_status','password']);
        if(empty($t_admin)){
            return ToolUtil::returnJson(401,'账号没注册');
        }
        if(empty($t_admin['password'])){
            return ToolUtil::returnJson(401,'不能密码登录');
        }

        if($t_admin['status']===0){
            return ToolUtil::returnJson(301,'账号冻结中，请联系管理员');
        }
        if($t_admin['status']===2){
            return ToolUtil::returnJson(301,'账号没有通过审核，请联系管理员');
        }
        if($t_admin['login_status']===1){
            $loginStatus = 2;
        }elseif ($t_admin['login_status']===2){
            $loginStatus = 1;
        }else{
            $loginStatus = 1;
        }

        $t_admin_data = AdminModel::queryFirst(['password'=>md5($param['password'].$t_admin['rand_num']),'id'=>$t_admin['id']],['id','username','sn_num','group_id','mobile']);
        if(empty($t_admin_data)){
            return ToolUtil::returnJson(401,'密码错误');
        }

        $param['remark'] = '小程序登录';
        $t_admin_data['equipment'] = [];
        $t_admin_data['sn'] = [];

        $parentSn = ParentSnModel::queryWhere(['admin_id'=>$t_admin_data['id']],['t_parent_sn.id','a.online','a.avatar','a.name','a.value as sn_value']);
        if(count($parentSn)){
            $arr = [];
            foreach ($parentSn as $key=>$value){
                $arr[] = $value;
            }
            $t_admin_data['sn'] = $arr;
        }
        
        $param['username'] = $t_admin_data['username'];
        $param['details'] = ToolUtil::handleSuccessOrError(['mobile'=>$param['username']]);
        LogUtil::addAdminLog($param);
        AdminModel::edit(['id'=>$t_admin_data['id']],['login_ip'=>ToolUtil::get_real_ip(),'login_time'=>time(),'login_status'=>$loginStatus]);
        return ToolUtil::returnJson(200,'成功',$t_admin_data);

    }

    /**
     * 编号获取用户信息和设备信息
     * @param $param
     * @return false|string
     */
    public static function queryIdAdmin($param){
        $data = AdminModel::queryFirst(['id'=>$param['userId']],
            ['id','username','sn_num','group_id']);
        if($data){
            $data['equipment'] = [];
            $data['sn'] = [];
            if($data['group_id']===4){
                $parentSn = ParentSnModel::queryWhere(['admin_id'=>$data['id']],['t_parent_sn.id','online','avatar','name','value']);
                if(count($parentSn)){
                    $arr = [];
                    foreach ($parentSn as $key=>$value){
                        $bind = BindSnModel::queryFirst(['sn_value'=>$value['value']],['status']);
                        if($bind['status']){
                            $arr[] = $value;
                        }
                    }
                    $data['sn'] = $arr;
                }
            }
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(301,'不存在该用户');
    }

    /**
     * 找回密码
     * @param $param
     * @return false|string
     */
    public static function retrievePassword($param){
        return ToolUtil::returnJson(301,'接口弃用');
        $randStr = ToolUtil::randStr();
        $data = [
            'password'=>md5($param['password'].$randStr),
            'update_time'=>time()
        ];
        $sms = SmsModel::queryFirst(['phone'=>$param['mobile'],'code'=>$param['smsCode']],['create_time']);
        if(!$sms){
            return ToolUtil::returnJson(301,'验证码不对或不存在该用户');
        }
        if(time()-300>$sms['create_time']){
            return ToolUtil::returnJson(302,'验证码超过有效期');
        }
        $int = AdminModel::edit(['mobile'=>$param['mobile']],$data);
        if($int){
            return ToolUtil::returnJson(200,'成功');
        }
        return ToolUtil::returnJson(300,'失败');
    }


    /**
     * 小程序注册
     * @param $param
     * @return false|string
     */
    public static function register($param){
        return ToolUtil::returnJson(301,'接口弃用');
        try {
            if($param['password']!==$param['password2']){
                return ToolUtil::returnJson(301,'两次密码不对');
            }
            $code = SmsModel::queryFirst(['phone'=>$param['phone'],'code'=>$param['code']],['id','create_time']);
            if($code){
                if((time()-300)>(int)$code['create_time']){
                    return ToolUtil::returnJson(304,'验证码时间超出');
                }
                DB::beginTransaction();
                $admin = AdminModel::queryFirstOrWhere(['username'=>$param['phone']],['mobile'=>$param['phone']],['id']);
                if($admin){
                    return ToolUtil::returnJson(303,'已存在该手机号或账户');
                }
                $randStr = ToolUtil::randStr();
                $group = GroupModel::queryFirst(['title'=>$param['title']],['id']);
                if($group['id']==3){
                    $mobile = AdminModel::queryFirst(['group_id'=>1],['mobile']);
                    AccountCenterService::joinClassSms($mobile);
                    $status = 2;
                }else{
                    $status = 1;
                }
                $groupId = $group['id'];
                $vipId = 4;
                $data = [
                    'username'=>$param['phone'],
                    'password'=>md5($param['password'].$randStr),
                    'mobile'=>$param['phone'],
                    'rand_num'=>$randStr,
                    'group_id'=>$groupId,
                    'create_time'=>time(),
                    'vip_id'=>$vipId,
                    'status'=>$status
                ];
                $param['remark'] = '注册';
                if(AdminModel::add($data)){
                    $param['details'] = ToolUtil::handleSuccessOrError(['username'=>$param['phone']]);
                    $param['username'] = $param['phone'];
                    LogUtil::addAdminLog($param);
                    $admin1 = AdminModel::queryFirst(['username'=>$param['phone']],['id']);
                    DB::commit();
                    return ToolUtil::returnJson(200,'注册成功',$admin1);
                }
                return ToolUtil::returnJson(300,'注册失败');
            }
            return ToolUtil::returnJson(302,'验证码不正确');
        }catch (\Exception $exception){
            DB::rollBack();
            return ToolUtil::returnJson(500,'网络拥堵，请稍后再试');
        }
    }

    /**
     * 获取个人信息
     * @param $param
     * @return false|string
     */
    public static function getUserInfo($param){
        $admin = AdminModel::queryWhere(['t_admin.id'=>$param['id']],
            ['t_admin.id','t_admin.username','t_admin.password','t_admin.nickname','t_admin.mobile','g.title','t_admin.sn_num','t_admin.group_id','t_admin.avatar']);
        if($admin){
            if($admin['group_id'] === 3){
                $admin['batchCount'] = BatchModel::queryWhereCount(['admin_id'=>$param['id']]);
            }

            $admin['password'] = empty($admin['password'])?0:1;
            return ToolUtil::returnJson(200,'成功',$admin);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 修改手机号
     * @param $param
     * @return false|string
     */
    public static function editMobile($param){

        $param['id'] = (int)$param['id'];
        $t_admin = DB::table('t_admin')->where('id',$param['id'])->first(['mobile','t_group_id']);
        if(empty($t_admin)){
            return ToolUtil::returnJson(301,'没有记录');
        }
        if($t_admin['mobile'] == $param['mobile']){
            return ToolUtil::returnJson(301,'没有修改');
        }
        $sms = DB::table('t_sms')->where(['phone'=>$t_admin['mobile'],'code'=>$param['code']])
            ->orderByDesc('create_time')->first(['create_time']);
        if(empty($sms)){
            return ToolUtil::returnJson(301,'验证码有误');
        }
        if(time()-300>$sms['create_time']){
            return ToolUtil::returnJson(301,'验证码超过有效期');
        }
        $param['remark'] = "修改手机号";
        $mobile_rec = DB::table('t_admin')->where(['t_group_id'=>$t_admin['t_group_id'],'mobile'=>$param['mobile']])->value('id');
        if($mobile_rec){
            return ToolUtil::returnJson(301,'已存在该手机号');
        }
        $param['details'] = ToolUtil::handleSuccessOrError(['username'=>$param['mobile']]);
        if(AdminModel::edit(['id'=>$param['id']],['mobile'=>$param['mobile'],'update_time'=>time()])){
            LogUtil::addAdminLog($param);
            return ToolUtil::returnJson(200,'成功');
        }
        return ToolUtil::returnJson(300,'失败');
        
    }

    /**
     * 设备编号获取设备信息
     * @param $param
     * @return false|string
     */
    public static function querySnInfo($param){
        $field = ['p.id','a.name','a.value','a.avatar','a.school','p.sn_grade_id as gradeName','p.teacher_id'];
        $parentSn = ParentSnModel::queryWhereFirst(['p.id'=>$param['id']],$field);
        if($parentSn){
            $bind = BindSnModel::queryFirst(['sn_value'=>$parentSn['value']],['status']);
            if(!$bind['status']){
                return ToolUtil::returnJson(301,'设备没有绑定');
            }
            $snGrade = SnGradeModel::queryFirst(['id'=>$parentSn['gradeName']],['class_name']);
            if($snGrade){
                $parentSn['gradeName'] = $snGrade['class_name'];
            }else{
                $parentSn['gradeName'] = '一年级';
            }
            $admin = AdminModel::queryFirst(['id'=>$parentSn['teacher_id']],['username']);
            $parentSn['tUsername'] = $admin['username'];
            return ToolUtil::returnJson(200,'成功',$parentSn);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 修改设备信息
     * @param $param
     * @return false|string
     */
    public static function updateParentSn($param){
        try {
            $param['remark'] = '修改设备信息';
            $parent = ParentSnModel::queryFirst(['id'=>$param['id']],['admin_sn_id']);
            if(!$parent){
                return ToolUtil::returnJson(301,'不存在该设备');
            }
            $parentSn = ParentSnModel::queryWhereFirst(['a.name'=>$param['name'],'p.admin_id'=>$param['userId']],['p.id']);
            if($parentSn){
                if($parentSn['id']!=$param['id']){
                    return ToolUtil::returnJson(302,'不能设置重复设备名称');
                }
            }

            if(!empty($param['school'])){
                $school = $param['school'];
            }else{
                $school = '';
            }

            if(!empty($param['gradeName'])){
                $grade = SnGradeModel::queryFirst(['class_name'=>$param['gradeName']],['id']);
                $grade = $grade['id'];
            }else{
                $grade = '';
            }

            DB::beginTransaction();
            $int = AdminSnModel::edit(['id'=>$parent['admin_sn_id']],['name'=>$param['name'],'school'=>$school,
                'avatar'=>$param['avatar'],'update_time'=>time()]);
            if($int){
                
                if(ParentSnModel::edit(['id'=>$param['id']],['sn_grade_id'=>$grade,'update_time'=>time()])){
                    DB::commit();
                    return ToolUtil::returnJson(200,'成功');
                }
            }
            return ToolUtil::returnJson(300,'失败');
        }catch (\Exception $exception){
            DB::rollBack();
            return ToolUtil::returnJson(500,'网络拥堵,请稍后再试');
        }
    }

    /**
     * 修改设备头像信息
     * @param $param
     * @return false|string
     */
    public static function updateAvatar($param){
        $param['remark'] = '修改设备头像信息';
        $parent = ParentSnModel::queryFirst(['id'=>$param['id']],['admin_sn_id']);
        if($parent){
            if(AdminSnModel::edit(['id'=>$parent['admin_sn_id']],['avatar'=>$param['avatar'],'update_time'=>time()])){
                $param['details'] = ToolUtil::handleSuccessOrError(['avatar'=>$param['avatar']]);
                LogUtil::addAdminLog($param);
                return ToolUtil::returnJson(200,'成功');
            }
            return ToolUtil::returnJson(300,'失败');
        }
        return ToolUtil::returnJson(301,'不存在该设备');
    }

    /**
     * 修改用户密码
     * @param $param
     * @return false|string
     */
    public static function editPassword($param){
        $sms = SmsModel::queryFirst(['phone'=>$param['phone'],'code'=>$param['smsCode']],['create_time']);
        $param['remark'] = '修改用户密码';
        if($sms){
            if((time()-120) < $sms['create_time']){
                $admin = AdminModel::queryFirst(['id'=>$param['userId']],['rand_num','username']);
                if($admin){
                    if(AdminModel::edit(['id'=>$param['userId']],['password'=>md5($param['password'].$admin['rand_num'])])){
                        $param['code']='success';
                        $param['details'] = ToolUtil::handleSuccessOrError($param);
                        LogUtil::addAdminLog($param);
                        return ToolUtil::returnJson(200,'成功');
                    }
                    unset($param['password']);
                    $param['details'] = ToolUtil::handleSuccessOrError($param);
                    LogUtil::addAdminLog($param);
                    return ToolUtil::returnJson(300,'失败');
                }
                return ToolUtil::returnJson(302,'没有该用户');
            }
            return ToolUtil::returnJson(302,'验证码超出有效期，请重新获取验证码');
        }
        return ToolUtil::returnJson(301,'验证码错误');
    }

    /**
     * 获取家长设备信息
     * @param $param
     * @return false|string
     */
    public static function getParentSn($param){
        $data = ParentSnModel::queryWhere(['t_parent_sn.admin_id'=>$param['userId'],'status'=>1],['t_parent_sn.id','a.avatar','a.name']);
        if(count($data)){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 获取设备信息
     * @param $param
     * @return false|string
     */
    public static function getSnInfo($param){
        $data = ParentSnModel::queryLeft(['t_parent_sn.id'=>$param['id'],'t_parent_sn.admin_id'=>$param['userId']],
            ['s.avatar','s.name','s.value','a.mobile','g.class_name as title','b.name as bName','s.school']);
        if($data){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 获取班级信息
     * @param $param
     * @return false|string
     */
    public static function getClassInfo($param){
        $data = BatchModel::queryWhere(['admin_id'=>$param['userId']],['name','rand_code','id']);
        if($data){
            foreach ($data as $key=>$value){
                $value['classCount'] = TeacherSnModel::queryWhereCount(['batch_id'=>$value['id']]);
                $data[$key] = $value;
            }
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 增加班级信息
     * @param $param
     * @return false|string
     */
    public static function addClass($param){
        $randNum = substr(time(),-6).$param['userId'];
        $int = BatchModel::add(['name'=>$param['name'],'admin_id'=>$param['userId'],'rand_code'=>$randNum,'create_time'=>time()]);
        $param['remark'] = '增加班级';
        if($int){
            $param['details'] = ToolUtil::handleSuccessOrError($param);
            LogUtil::addAdminLog($param);
            return ToolUtil::returnJson(200,'成功');
        }
        return ToolUtil::returnJson(300,'失败');
    }

    /**
     * 获取班级sn信息
     * @param $param
     * @return false|string
     */
    public static function getClassSnInfo($param){
        $data = TeacherSnModel::queryClassInfo(['b.id'=>$param['id']]);
        if(count($data)){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }
}